<?php

use \Entities;
use Engine\Auth\CurrentUser as USER;
use Engine\Functions\ParseAndConvert as FUNCTS;
use Engine\Constants\GLConstants as CONSTS;


require_once 'Zend/View/Helper/HeadTitle.php';

class IndexController extends Zend_Controller_Action {

    public function init() {

        $viewManager = new \Managers\View();
        $this->view->allTypes = $viewManager->getAllTypes();
        
        $user = new \Entities\Profile();

    }

    public function indexAction() {

    }

    public function viewmessageAction() {
        $messageId = $this->_getParam('messageId');
        $this->view->parentId = $messageId;
        
        
        $commentForm = new Zend_Form();
        $commentForm->setAction($this->view->url(array('messageId'=>$messageId), 'message'));
        $commentForm->setMethod('POST');
        
        
        $hiddenParent = new Zend_Form_Element_Hidden('parentId');
        $hiddenParent->setValue($messageId);
        
        $userName = new Zend_Form_Element_Text('userName');
        
        if (USER::getId()) {
        	$userName->setValue(Engine\Auth\CurrentUser::getData()->getNickName());
        	$userName->setAttrib('readonly', 'readonly');
        } else {
        	$userName->setValue('Назови свое имя, непредставившийся');
        }
        
        
        $commentText = new Zend_Form_Element_Textarea('commentText', array('cols' => 64, 'rows' => 7));
        $submit = new Zend_Form_Element_Submit('submit', array('label' => 'Оставить неизгладимое впечатление'));
        
        $commentForm->addElements(array($userName, $commentText, $submit, $hiddenParent));
        
        foreach ($commentForm->getElements() as $element) {
            $element->setDecorators(array('viewHelper', 'Errors'));
        }
        
        $commentForm->setDecorators(array(
        	array('ViewScript', 
        		array('viewScript' => 'index/forms/comment.phtml')
        	)
        ));
        
        $this->view->form = $commentForm;
        $messagesManager = new \Managers\Message();
        $this->view->allCounts = $messagesManager->getAllMessagesChildsCounts();

        
        if ($messageId > 0) {
            
            $thisMessage = $messagesManager->getMessage($messageId);
            
            
            $allContent = $messagesManager->getMessageChilds($messageId, true);
            $this->view->creatorId = $thisMessage->getUser()->getUserId();
            
            
            Zend_Layout::startMvc();
            $layout = Zend_Layout::getMvcInstance();
            $view = $layout->getView();
            
            
            
            
            $view->headTitle($thisMessage->getTitle());
            
            $view->headMeta()->appendName('description', $thisMessage->getSeoOptions());
            $view->headMeta()->appendName('keywords', $thisMessage->getKeyWords());
            
            
            $this->view->allComments = $messagesManager->getAllComments($messageId);
            $this->view->moreFromThisCatergory = $messagesManager->getLastParents(false, $thisMessage->getType()->getTypeId());
            $this->view->viewMessageId = $thisMessage->getMessageId();
            $this->view->viewMessage = $thisMessage;
			
//            $this->view->allResponces = $messagesManager->
            
        } else {
            $allContent = $messagesManager->getMessageChilds();
            $this->view->viewMessageId = false;
			
        }

        $this->view->allParents = $allContent;
        

        $randomMessages = $messagesManager->getLastParents();
        shuffle($randomMessages);
        $randMessLimited = array();
        for($i=0; $i<7; $i++){
             $randMessLimited []= $randomMessages[$i];
        }
        
        $this->view->randomMessages = $randMessLimited;
        
    }

    public function messagesAction() {
					
        $params = $this->_getAllParams();
		
        $messagesManager = new \Managers\Message();
        
        $this->view->randomAphorisms = $messagesManager->getRandomAphorism(4);
        
        
        if(!isset($params['type'])){
            $params['type'] = 'all';
        }
        
        if ($params['type'] == 'all'){
            $this->view->allParents = $messagesManager->getLastParents();
        }else{
            $this->view->allParents = $messagesManager->getLastParents(false, $params['type']);
        }
        
        $this->view->allAttached = $messagesManager->getAttachedMessages();
        $typesArray = $messagesManager->getAllMessageTypes();
        
        
        foreach($typesArray as $key=>$type){
            if($params['type'] == $type->getTypeId()){
                $this->view->viewType = $key;
                break;
            }
        }
        
        if (!$this->view->viewType) {$this->view->viewType = 'all';} else{
            $this->view->viewType = $this->view->viewType;
        }
        
        $this->view->allMessageTypes = $typesArray;
        
        
        $this->view->allHistory = $messagesManager->getHistory(6);
        $this->view->allMessages = $messagesManager->getAllMessages();
        $this->view->allQuickNews = $messagesManager->getAllQuickNews();

        $allMessages = $messagesManager->getAllMessages(true);
		
		$messagesArray = array();

		foreach($allMessages as $oneMessage){
			$messagesArray[$oneMessage->getMessageId()] = $oneMessage->getTitle();
		}

        
	 
		$this->view->allMessagesTitles = $messagesArray; 
        
            
        Zend_Layout::startMvc();
        $layout = Zend_Layout::getMvcInstance();
        $view = $layout->getView();
        $view->headMeta()->appendName('description', "Ресурс с рабочим именем 'Полезные Штуки' призван не только объеденять пользователей и разработчиков, поднимать и решать всякие вопросы, ставить задачи и находить решения. Мы хотим, чтобы для каждого из нас он стал Личным Помощником, Консультантом в тяжелых вопросах, да и просто таким себе 'Развлекатором-в-свободное время'");
        $view->headTitle('Добро пожаловать на deeflow.com');
		
    }

    public function messagesboxedAction() {
					
        $params = $this->_getAllParams();
        $messagesManager = new \Managers\Message();
        
        $this->view->randomAphorisms = $messagesManager->getRandomAphorism(4);
        
        
        if(!isset($params['type'])){
            $params['type'] = 'all';
        }
        
        if ($params['type'] == 'all'){
            $this->view->allParents = $messagesManager->getLastParents();
        }else{
            $this->view->allParents = $messagesManager->getLastParents(false, $params['type']);
        }
        
        $this->view->allAttached = $messagesManager->getAttachedMessages();
        $typesArray = $messagesManager->getAllMessageTypes();
        
        
        foreach($typesArray as $key=>$type){
            if($params['type'] == $type->getTypeId()){
                $this->view->viewType = $key;
                break;
            }
        }
        
        if (!$this->view->viewType){$this->view->viewType = 'all';}
        
        $this->view->allMessageTypes = $typesArray;
        
        
        $this->view->allHistory = $messagesManager->getHistory(6);
        $this->view->allMessages = $messagesManager->getAllMessages();
        $this->view->allQuickNews = $messagesManager->getAllQuickNews();

        $allMessages = $messagesManager->getAllMessages(true);
		
		$messagesArray = array();

		foreach($allMessages as $oneMessage){
			$messagesArray[$oneMessage->getMessageId()] = $oneMessage->getTitle();
		}
	
		$this->view->allMessagesTitles = $messagesArray; 
        
            
        Zend_Layout::startMvc();
        $layout = Zend_Layout::getMvcInstance();
        $view = $layout->getView();
        $view->headTitle('Добро пожаловать на deeflow.com');
		
    }

	public function allusersAction() {
		$profileManager = new \Managers\Profile();
        $this->view->allUsers = $profileManager->getUsers();
		
	}	
	
	public function historyAction() {
		$messageManager = new \Managers\Message();
        $this->view->allHistory = $messageManager->getHistory();

		$allMessages = $messageManager->getAllMessages(true);
		
		$messagesArray = array();

		foreach($allMessages as $oneMessage){
			$messagesArray[$oneMessage->getMessageId()] = $oneMessage->getTitle();
		}
	
		$this->view->allMessagesTitles = $messagesArray;
        Zend_Layout::startMvc();
        $layout = Zend_Layout::getMvcInstance();
        $view = $layout->getView();
        $view->headTitle('История событий deeflow');
	}

	public function createmessageAction() {
        
        if (!USER::getId()){
            $this->_redirect($this->view->url(array(), 'login'));  
        }
        
        $profileManager = new \Managers\Profile();
        $this->view->allUsers = $profileManager->getUsers();

        $messagesManager = new \Managers\Message();
        $this->view->allMesseges = $messagesManager->getLastParents();
        $this->view->allMessegetTypes = $messagesManager->getAllMessageTypes();

        $globalNowDateTime = new DateTime();
        $this->view->globalNowDateTimeString = $globalNowDateTime->format("Y-m-d H:i:s");

        $allParams = $this->_getAllParams();
        
        $this->view->messageIdFromGet = $this->_getParam('messageId');
        
        
        $messageManager = new \Managers\Message();
        
        if ($this->view->messageIdFromGet != -1) {
                $editedMessage = $messageManager->getMessage($this->view->messageIdFromGet);
                $this->view->editedMessage = $editedMessage;
                $this->view->childsMessages = $messageManager->getMessageChilds($this->view->messageIdFromGet, false);
//          $this->_redirect ($view->url(array('messageid'=>$editedMessage->getMessageId()), 'addmessage')); 
       }
        
        if ($this->getRequest()) {
            $logManager = new \Managers\AutoLog();
            if ($this->_request->getParam('submitPublicate') || $this->_request->getParam('submitSaveInDrafts')) {
                $newMessage = $messageManager->addMessage($allParams);
                
                $redirectToMessage = $newMessage->getParentId();
                
                
                
                
                        
                if ($this->_request->getParam('submitPublicate') && $this->_getParam('messageIdFromGet')!="-1") {
                        $logManager->createLogEntity(CONSTS::$LOG_CONST['FIX_PUB'], $newMessage->getParentId(), USER::getData());
                }else{
                    if($this->_getParam('parentId') == 'new'){
                        $logManager->createLogEntity(CONSTS::$LOG_CONST['ADD_PUB'], $newMessage->getMessageId(), USER::getData());
                    }else{
                        if ($newMessage->getMessageId() != $newMessage->getParentId()){
                            $logManager->createLogEntity(CONSTS::$LOG_CONST['UPD_PUB'], $newMessage->getParentId(), USER::getData());
                        }else{
                            $logManager->createLogEntity(CONSTS::$LOG_CONST['UPD_PUB'], $newMessage->getParentId(), USER::getData());
                        }
                    }
                }
                
                $this->_redirect($this->view->url(array('messageId' => $redirectToMessage), 'addmessage'));
            } 
        }
    }
    
    public function addcommentAction(){
        $profileManager =  new \Managers\Profile();
        $user = $profileManager->getUser(USER::getId());
        
        $commentsManager = new \Managers\Message();
        
        $params = $this->_getAllParams();
        
        $commentsManager->addComment($user, $params);
        $this->_redirect($this->view->url(array('messageId' => $params['parentId']), 'message'));
        
    }
    
    public function addresponceAction(){
        
        $params = $this->_getAllParams();
        print "<pre>";
        print_r($params);
        print "</pre>";
        die("++");
    }
    
    public function getrandomaphorismsajaxAction(){
        $params = $this->_getAllParams();
        $messagesManager = new \Managers\Message();
        $aphorisms = $messagesManager->getRandomAphorism($params['count']);
            $array = array();
            foreach ($aphorisms as $key => $value) {
                $array[$key]=array('id'=>$value->getAphorismId(), 'text'=>$value->getText(), 'author'=>$value->getTheme());
            }
            
        print json_encode($array);
        die;
    }
    
    public function userviewAction(){
	 
	 		
		
	 $params = $this->_getAllParams();
       if($params['userid']!=0){
	   $profileManager = new \Managers\Profile();
           $messageManager = new \Managers\Message();
			$allMessages = $messageManager->getAllMessages(true);
			
			$messagesArray = array();

			foreach($allMessages as $oneMessage){
				$messagesArray[$oneMessage->getMessageId()] = $oneMessage->getTitle();
			}
		
			$this->view->allMessagesTitles = $messagesArray;
	   
           
           $this->view->user=$profileManager->getUser($params['userid']);
           $this->view->usersPosts = $messageManager->getLastParentsByUser($params['userid']);
           $this->view->usersComments = $messageManager->getAllCommentsByUser($params['userid']);
		   
       }
       
    }
    
    public function recreatehistoryAction(){
        
        if(USER::getId() == 1){
            $logManager = new \Managers\AutoLog();
            $history = $logManager->recreateHistory();
            $this->_redirect('./history');
        }else{
            if($_SERVER['HTTP_REFERER']){
                $this->_redirect($_SERVER['HTTP_REFERER']);
            }else{
                $this->_redirect('./history');
            }
        }
    }
    
    public function videoAction(){
        $messagesManager = new \Managers\Message();

        
        $params = $this->_getAllParams();
       
        if(isset($params['count'])){
            $countPerPage = $params['count'];
        }else{
            $countPerPage=10;
        }
        
        
        if(isset($params['start'])){
            $startPage = $params['start'];
        }else{
            $startPage = 0;
        }
        
        
        $count = $messagesManager->getAllVideosCount();
        
        $allVideos=$messagesManager->getLastParents(false, '6');
        
        if(($startPage+1)*$countPerPage <= $count){
            
            $videos = array();
            for($i=$startPage*$countPerPage; $i<$startPage*$countPerPage+$countPerPage; $i++){
                $videos[]= $allVideos[$i];
            }
            
            $this->view->activeVideos = $videos;
        }else{
            $this->view->activeVideos = $allVideos;
        }
        
        
        $links = array();
        
        
        for($i=0; $i<floor($count/$countPerPage); $i++){
            $temp = array();
            $temp['caption'] = 'page '.$i;
            $temp['url'] = 'start='.$i*$countPerPage.'&count='.$countPerPage;
            $links[]= $temp;
        }
        
        $this->view->paginate = $links;
    }
    
    public function searchAction(){
        $messagesManager = new \Managers\Message();
        
        $allMessages = $messagesManager->getAllMessages();
        
        $params = $this->_getAllParams();
       
        if(isset($params['query'])){
            if (strlen($params['query'])){
                $this->view->query = $params['query'];
                $this->view->searchResultMessages = $messagesManager->getMessagelikeText($params['query']);
            }
        }
        
        
        
        if(isset($params['queryApho'])){
            if (strlen($params['queryApho'])>0){
                $this->view->queryApho = $params['queryApho'];
                $this->view->searchResultAphorisms = $messagesManager->getApholikeText($params['queryApho']);
            }
        }


        Zend_Layout::startMvc();
        $layout = Zend_Layout::getMvcInstance();
        $view = $layout->getView();
        $view->headTitle($params['queryApho'].' - поиск на deeflow.com');
        $view->headMeta()->appendName('description', 'Афоризмы '.$params['queryApho']);
        
    }
}

?>
